/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hhdTScene.h"
#include "hhdIDirector.h"
#include "hhdIGame.h"
#include "hhdContentLibrary.h"
#include "hhdMessenger.h"
#include "hhdMScenePaused.h"
#include "hhdMSceneResumed.h"
#include "hhdFileHelpers.h"

#include "hhdTPrefab.h"
#include "hhdInteger.h"
#include "hhdGameObject.h"

#include "hhdGUIPanel.h"

#include "tinyxml.h"
#ifdef _OPENMP
#include <omp.h>
#endif

namespace hhd
{
    ContentCPP(hhd::TScene, TScene);
	HHD_REGISTRANT_CPP(IContent, TScene);

    TScene::TScene()
		: _game_object_table(3, 1)
		, _scene_processes_completed(hhd::SPC_NONE)
    {
        _scene_phase = None;
        _parent_game = NULL;
        _root_game_object = NULL;
        _root_gui_panel = NULL;
        _table_dirty = true;
        _table_dirty_layer = 0;
    }

    TScene::~TScene()
    {

    }

    void TScene::setDirtyLayer(int in_layer)
    {
        if(in_layer < 0)
        {
            error("Invalid Dirty Layer");
        }
        _table_dirty = true;
        if(in_layer < _table_dirty_layer)
        {
            _table_dirty_layer  = in_layer;
        }
    }

    void TScene::buildGameObjectTable()
    {
        _game_object_buffer.clear();
        // add list of gameobjects above the dirty layer to buffer
        for(int k = 0; k < _game_object_table.width(_table_dirty_layer); k++)
        {
            _game_object_buffer.add(_game_object_table[_table_dirty_layer][k]);
        }

        _game_object_table.clearBelow(_table_dirty_layer);

        while(_game_object_buffer.size() > 0)
        {
            // pop game object off stack
            GameObject* current = _game_object_buffer.removeLast();
            // set the game objects layer based on parent
            if(current->_parent_game_object != NULL)
            {
                current->_layer = current->_parent_game_object->_layer+1;
            }
            // add to the table
            while(_game_object_table.rows() <= current->_layer)
            {
                _game_object_table.addRow();
            }
            _game_object_table.add(current->_layer, current);
            // get number of children
            int children = current->_child_game_objects.size();

            // get our child game object buffer
            GameObject* const*  child_buffer = current->_child_game_objects;
            ///  push them all on the stack
            for(int k = 0; k < children; k++)
            {
                _game_object_buffer.add(child_buffer[k]);
            }
        }

        _table_dirty = false;
        _table_dirty_layer = Integer::MaxInt;

    }

    struct updateParams
    {
        const GameTimer* gt;
        GameObject** row;
        int width;
    };

    // called by game on each frame
    void TScene::update(const GameTimer& in_gt)
    {
		//baw	Really need to change this to have each director update its owned components
		//		instead. I'd expect to see better performance that way.

        _scene_phase = GameObjectUpdate;

        //update the root gui panel
        if(_root_gui_panel)
        {
            _root_gui_panel->update(in_gt);
        }

        // iterative update
        if(_table_dirty)
        {
            buildGameObjectTable();
        }
		
		for(int k = 0; k < _game_object_table.rows(); k++)
		{
			int row_width = _game_object_table.width(k);

			if(row_width == 0)
			{
				break;
			}

			GameObject** row = _game_object_table[k];
			for(int j = 0; j < row_width; j++)
			{
				row[j]->shallowUpdate(in_gt);
			}
		}

        // sync point
        _scene_phase = DirectorUpdate;

        // update directors
        for(size_t k = 0; k < _directors.size(); k++)
        {
            _directors[k]->update(in_gt);
        }
    }

    void TScene::draw()
    {
        for(size_t k = 0; k < _directors.size(); k++)
        {
            _directors[k]->draw();
        }
    }

    // add a director to this scene
    void TScene::addDirector(IDirector* in_director, bool is_drawable)
    {
        _director_map.add(in_director->directorName(), in_director);
        _directors.add(in_director);
        in_director->setScene(this);
    }

    // get a director pointer by type
    IDirector* TScene::getDirector(const String& in_name)
    {
        IDirector* result = NULL;
        _director_map.tryGetValue(in_name, result);
        /*if(result == NULL)
        {
        	StringBuilder sb;
        	sb << "Could not find director of type \'" << in_name << "\' in scene";
        	throw Exception(sb);
        }*/
        return result;
    }

    // add a named game object to this scene
    void TScene::addGameObject(GameObject* in_game_object)
    {
        //see if there is any game objects with this name already.
        if( _game_object_map.contains( in_game_object->name() ) )
        {
            Vector<GameObject*>& list_with_ins_name = _game_object_map[in_game_object->name()];
            list_with_ins_name.add( in_game_object );
        }
        else
        {
            _game_object_map.add( in_game_object->name(), Vector<GameObject*>() );
            Vector<GameObject*>& list_with_ins_name = _game_object_map[in_game_object->name()];
            list_with_ins_name.add( in_game_object );
        }
    }

    // get back a game object by it's name
    GameObject* TScene::getGameObject(const String& in_name)
    {
        if( _game_object_map.contains( in_name ) )
        {
            Vector<GameObject*>& list = _game_object_map[ in_name ];

            //just return the first one
            return list.first();
        }
        else
        {
            return NULL;
        }

    }

    Vector<GameObject*>* TScene::getGameObjects(const String& in_name)
    {
        if( _game_object_map.contains( in_name ) )
        {
            Vector<GameObject*>& list = _game_object_map[ in_name ];
            Vector<GameObject*>* result = &list;
            //just return the first one
            return result;
        }
        else
        {
            return NULL;
        }
    }

    // remove a game object from the scene by it's name
    void TScene::RemoveReleaseGameObject(GameObject* in_to_remove)
    {
        if( _game_object_map.contains( in_to_remove->name() ) )
        {
            Vector<GameObject*>& list = _game_object_map[ in_to_remove->name() ];
            list.remove( in_to_remove );
        }
        else
        {
            error("Attempting to remove a GameObject from the Scene but There are no GameObjects in the Scene with it's name");
        }
    }

    void TScene::setRootGameObject(GameObject* in_game_object)
    {
        in_game_object->_owner = this;
        _root_game_object = in_game_object;
    }

    GameObject* TScene::getRootGameObject()
    {
        return _root_game_object;
    }

    void TScene::addGUIPanel(GUIPanel* in_gui_panel)
    {
        _gui_panel_map.add(in_gui_panel->name(), in_gui_panel);
    }

    GUIPanel* TScene::getGUIPanel(const String& in_name)
    {
        GUIPanel* panel_result = NULL;
        _gui_panel_map.tryGetValue(in_name, panel_result);
        return panel_result;
    }

    void TScene::setRootGUIPanel(GUIPanel* in_panel)
    {
        in_panel->_parent_scene = this;
        _root_gui_panel = in_panel;
    }

    GUIPanel* TScene::getRootGUIPanel()
    {
        return _root_gui_panel;
    }

    TScene* TScene::loadScene(const String& in_path)
    {
		TScene* result = new TScene();
        result->create(in_path);

        return result;
    }

    void TScene::initialize()
    {
        this->_scene_phase = MessageHandling;
        //hout << *_root_game_object;
        _root_game_object->initialize();

        if(_root_gui_panel)
        {
            _root_gui_panel->initialize();
        }

        for(size_t k = 0; k < _directors.size(); k++)
        {
            _directors[k]->initialize();
        }
    }

    void TScene::create(const char8_t* in_path)
    {
		_path = in_path;
        _scene_phase = Loading;

		String xml_string;
		getFileContents(xml_string, _path);
		TiXmlDocument document;
		document.Parse(xml_string);

		const TiXmlElement* root_element = document.RootElement();

        const TiXmlElement* game_object_xml_element = NULL;
        const TiXmlElement* gui_panel_xml_element = NULL;

		for(const TiXmlElement* child_element = root_element->FirstChildElement();
			child_element != NULL;
			child_element = child_element->NextSiblingElement())
        {
            const char8_t* tag = child_element->Value();

            if(String::equals("GameObject", tag))
            {
                // parse a game object
                HHD_ASSERT(_root_game_object == NULL)

				game_object_xml_element = child_element;

				GameObject* go = Factory::acquire<GameObject>();
				setRootGameObject(go);

				String root_xml(*game_object_xml_element);
				_root_game_object->readXML(root_xml, this);
				_root_game_object->setOwner( this );
				_root_game_object->_layer = 0;

				_game_object_table.addRow();
				_game_object_table.add(0, _root_game_object);
            }
            else if(String::equals("Director", tag))
            {
                const char8_t* director_type = child_element->Attribute("type");
                if(director_type != NULL)
                {
                    IDirector* director = Registry<IDirector>::createFromRegistry(director_type);
                    if(director == NULL)
                    {
                        StringBuilder sb;
                        sb << "Could not find prototype Director of type \"" << director_type << "\"" << endl;
                        sb << director_type << " needs to be added to your scene and registered in Game::registerDirectorClasses()";
						String string;
						sb >> string;
                        error( string );
                    }
                    addDirector(director);
                    director->deserializeFromXML(child_element);
                }
            }
            else if(String::equals("Prefab", tag))
            {
                ContentLibrary::loadContent<TPrefab>(child_element->Attribute("path"));
            }
            else if(String::equals("AssetList", tag))
            {
                ContentLibrary::loadAndParseAssetList( child_element->Attribute("path") );
            }
            else if(String::equals("GUIPanel", tag))
            {
                HHD_ASSERT(_root_gui_panel == NULL);

				gui_panel_xml_element = child_element;

                GUIPanel* gp = Factory::acquire<GUIPanel>();
                setRootGUIPanel(gp);
                String root_xml(*gui_panel_xml_element);
                _root_gui_panel->readXML(root_xml, this);
                _root_gui_panel->setScene( this );
            }
            else
            {
                HHD_ASSERT( !"Error parsing XML node" );
            }
        }
        // we have to parse gameobject last because may depend on scene's directors
        HHD_ASSERT(game_object_xml_element != NULL);
    }

    IGame* TScene::getGame()
    {
        return _parent_game;
    }

    void TScene::registerForMessages(IDirector* in_director)
    {
        _messaged_directors.add(in_director);
    }

    void TScene::registerForMessages(IComponent* in_component)
    {
        _messaged_components.add(in_component);
    }

    void TScene::pause()
    {
        this->sendMessage(Factory::acquire<MScenePaused>());
    }

    void TScene::resume()
    {
        this->sendMessage(Factory::acquire<MSceneResumed>());
    }

    void TScene::reset()
    {
        if(this->_root_game_object)
        {
            Factory::release( this->_root_game_object );
        }

        if(this->_root_gui_panel)
        {
            Factory::release(this->_root_gui_panel);
        }

        for( size_t i = 0; i < this->_directors.size(); i++ )
        {
            Factory::release( _directors[i] );
        }

        IGameObjectTreeHolder::reset();

        _scene_phase = None;
    }
}
